// 和用户相关的状态管理

import { createSlice } from '@reduxjs/toolkit'
import { setToken as _setToken, getToken, removeToken } from '@/utils' /* 这里用as重命名 防止setToken重名 */
import { loginAPI, getProfileAPI } from '@/apis/user'

// 创建userSlice
const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '', /* 默认取本地 次redux */
    userInfo: {} /* 用户信息 */
  },

  // 同步修改方法 token/信息/清空
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      _setToken(action.payload)/* 将后端取到的token 实参传入token.js持久化处理 */
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

// 解构出actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer
// 异步方法封装 完成登录获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
  }
}
// 获取用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

export { fetchLogin, fetchUserInfo, clearUserInfo  }

export default userReducer